// General WeChat payment call
// ===========================

;(function(global, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['wx'], factory)
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory(require('wx'))
  } else {
    global.wxUpload = factory(global.wx)
  }
})(this, function(wx) {
  var Wxupload = {

    injectConfig: function(config) {

      var isDebug = location.search.indexOf('debug=true') > 0
      var apis =  ['chooseImage', 'previewImage', 'uploadImage']
      
      if(isDebug) {
        alert(JSON.stringify(config))
      }
      
      wx.config({
        debug: isDebug,
        appId: config.appid,
        timestamp: config.timestamp,
        nonceStr: config.nonceStr,
        signature: config.signature,
        jsApiList: apis
      })
    },

    invokeUpload: function(chooseCallback, successFunction) {

      var that = this

      wx.ready(function() {
        wx.chooseImage({
          count: 1, // 默认9,这里只开放一张,因为下载接口只能单张下载！
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            chooseCallback(localIds[0]);
            that.uploadImage(localIds[0], successFunction)
          }
        })
      })
    },

    uploadImage: function(localId, successFunction) {

      var that = this,
          serverId = null;

      function upload() {  // 单张上传
        wx.uploadImage({
          localId: localId,
          success: function (res) {
            serverId = res.serverId;
            successFunction(serverId);
          },
          fail: function (res) {
            alert(JSON.stringify(res)); // 上传失败
          }
        });
      }

      upload();
    }

  }

  return Wxupload
})